<template>
  <div class="register-section">
    <n-space vertical>
      <n-space justify="space-between">
        <n-gradient-text
          class="back"
          @click="backToLogin"
          :gradient="{ from: '#ffa364', to: '#ff7416' }"
        >
          ←前往登录
        </n-gradient-text>
        <n-gradient-text type="info" class="title"> 注册 </n-gradient-text>
      </n-space>
      <div class="gap" style="border-top: 1px solid #f1f1f1"></div>

      <n-form
        :model="formValue"
        :rules="rules"
        ref="formRef"
        :show-label="false"
      >
        <n-form-item path="username">
          <n-input
            placeholder="用户名"
            round
            v-model:value="formValue.username"
          >
            <template #prefix>
              <n-icon>
                <flash-outline />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="email">
          <n-input placeholder="邮箱" round v-model:value="formValue.email">
            <template #prefix>
              <n-icon>
                <flash-outline />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="password">
          <n-input
            type="password"
            show-password-toggle
            placeholder="密码"
            :maxlength="8"
            round
            v-model:value="formValue.password"
            @input="handlePasswordInput"
          >
            <template #prefix>
              <n-icon>
                <flash-outline />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item
          first
          path="rePassword"
          label="重复密码"
          ref="rPasswordFormItemRef"
        >
          <n-input
            placeholder="重复输入密码"
            :disabled="!formValue.password"
            v-model:value="formValue.rePassword"
            type="password"
            show-password-toggle
            @keydown.enter.prevent
            round
          >
            <template #prefix>
              <n-icon>
                <flash-outline />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item>
          <n-button size="large" @click="handleRegister" type="primary" block
            >注&nbsp;册
          </n-button>
        </n-form-item>
      </n-form>
    </n-space>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { FlashOutline, ArrowBackCircle } from '@vicons/ionicons5';
import { User } from '@api/user';

import { useRouter } from 'vue-router';
import { useMessage } from 'naive-ui';

const message = useMessage();
const router = useRouter();

const formRef = ref(null);
const rPasswordFormItemRef = ref(null);
const formValue = reactive({
  username: '',
  password: '',
  rePassword: '',
  email: '',
});

//邮箱验证
function validateEmail(rule: any, value: any) {
  const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  return formValue.email && reg.test(formValue.email);
}
//密码起头验证
function validatePasswordStartWith(rule: any, value: any) {
  return (
    formValue.password &&
    formValue.password.startsWith(value) &&
    formValue.password.length >= value.length
  );
}
//密码相同验证
function validatePasswordSame(rule: any, value: any) {
  return value === formValue.password;
}

const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
    },
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
    },
    {
      validator: validateEmail,
      message: '请输入正确的邮箱',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
    },
  ],
  rePassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur'],
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input',
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input'],
    },
  ],
};
const handlePasswordInput = () => {
  if (formValue.rePassword) {
    (rPasswordFormItemRef.value as any).validate({ trigger: 'password-input' });
  }
};
const handleRegister = (e: any) => {
  e.preventDefault();
  (formRef.value as any).validate((errors: any) => {
    if (!errors) {
      User.register({
        email: formValue.email,
        username: formValue.username,
        password: formValue.password,
      }).then((res: any) => {
        console.log(res);
        if (res.data.status === 200) {
          message.success('注册成功');
          backToLogin();
        } else {
          message.error('注册失败');
        }
      });
    }
  });
};

const emit = defineEmits(['after']);
const backToLogin = () => {
  emit('after');
};
</script>

<style scoped lang="scss">
.register-section {
  padding: 8%;
}
.gap {
  height: 2vh;
}
.title {
  font-size: 1.8rem;
  font-weight: 600;
}
.back {
  cursor: pointer;
  margin-top: 2.5vh;
  margin-left: 0.1vw;
  font-size: 1rem;
  font-weight: 600;
}
</style>
